In this article, we will learn how to disable an item (option) using C#. After disabling it, the user will not be able to select the DropDownList
.
How to Disable a DropDownList first item in Asp.Net using C#
Let’s create a simple table ‘customers’ as shown below:
CustomerId (INT),
CustomerName (NVARCHAR 50)
CustomerEmail (NVARCHAR 50)
SQL
SET ansi_nulls ON go SET quoted_identifier ON go CREATE TABLE [dbo].[customers] ( [customerid] [INT] IDENTITY(1, 1) NOT NULL, [customername] [NVARCHAR](50) NULL, [customeremail] [NVARCHAR](50) NULL ) ON [PRIMARY] go
HTML
Now create a Webpage and add a DropDownList
control to it, which will be populated from the database.
<asp:DropDownList ID = "ddlCustomers" runat="server"> </asp:DropDownList>
You will need to import the following namespaces:
using System.Data; using System.Data.SqlClient;
Once the DropDownList
is populated with the data, a default item is inserted at the first position and is selected. Then the default item is disabled by setting the ‘disabled’ attribute of the item.
public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { string conn_str = "Data Source=ServerName;Initial Catalog=dbName;Integrated Security=True"; using (SqlConnection con = new SqlConnection(conn_str)) { using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers")) { cmd.CommandType = CommandType.Text; cmd.Connection = con; con.Open(); ddlCustomers.DataSource = cmd.ExecuteReader(); ddlCustomers.DataTextField = "CustomerName"; ddlCustomers.DataValueField = "CustomerId"; ddlCustomers.DataBind(); con.Close(); } } ddlCustomers.Items.Insert(0, new ListItem("Select a customer", "")); ddlCustomers.Items[0].Attributes["disabled"] = "disabled"; } } }
Comments